package com.cookie.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/cookieLogin")
public class CookieServletLogin extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if ("admin1".equals(username) && "1".equals(password)) {
            /*当且仅当登录成功,由服务器创建Cookie,共享指定数据
            public Cookie(String name,String value)
            特点:
            只能共享String类型的数据,name表示作用域名,value表示作用域共享的数据值*/
            Cookie cookie = new Cookie("username", username);
            //将服务器创建好的Cookie对象响应给浏览器
            resp.addCookie(cookie);
            req.getRequestDispatcher("/cookieSuccess").forward(req, resp);
        } else {
            req.setAttribute("loginMsg", "账号密码错误");
            req.getRequestDispatcher("/login/jsp").forward(req, resp);
        }
    }
}
